import { TodoList } from "./types";
import {
  getTodoLists,
  addTodo as addTodoAPI,
  IToggleTodoStatus,
  toggleTodoStatus as toggleTodoStatusAPI,
  deleteTodoItem,
} from "./../../api/mongoAPI";
import { Dispatch } from "react";
import { Actions, Todo, ID } from "./types";

// interface IFetchTodoListAction {
//   (payload: TodoList): { type: Actions.FETCH_TODO_LIST; payload: TodoList };
// }
type IFetchTodoListAction = (payload: TodoList) => {
  type: Actions.FETCH_TODO_LIST;
  payload: TodoList;
};

const fetchTodoListAction: IFetchTodoListAction = payload => ({
  type: Actions.FETCH_TODO_LIST,
  payload,
});

export const fetchTodoList =
  () => async (dispatch: Dispatch<ReturnType<IFetchTodoListAction>>) => {
    const todoList = await getTodoLists();
    if (todoList) dispatch(fetchTodoListAction(todoList));
  };

// add
export type PartialTodo = Partial<Todo> & {
  content: string;
  reminderTime: Date;
};

export interface IAddTodoAction {
  type: Actions;
  payload: Todo;
}

const addTodoAction = (todo: Todo): IAddTodoAction => ({
  type: Actions.ADD_TODO,
  payload: todo,
});

export const addTodo =
  (todo: PartialTodo) => async (dispatch: Dispatch<IAddTodoAction>) => {
    const item = await addTodoAPI(todo);
    console.log(item);
    dispatch(addTodoAction(item));
  };
// remove
export interface IRemoveTodoAction {
  type: Actions;
  payload: ID;
}

const removeTodoAction = (ID: ID): IRemoveTodoAction => ({
  type: Actions.REMOVE_TODO,
  payload: ID,
});

export const removeTodo =
  (ID: ID) => (dispatch: Dispatch<IRemoveTodoAction>) => {
    dispatch(removeTodoAction(ID));
    deleteTodoItem({ id: ID })
      .then(res => {
        console.log("res", res);
      })
      .catch(err => {
        console.log("err", err);
        //本地删了 后台却删除失败的情况下 重新获取数据
        //@ts-ignore
        fetchTodoList()(dispatch);
      });
  };
// toggle
export interface IToggleTodoStatusAction {
  type: Actions.TOGGLE_TODO_STATUS;
  payload: ID;
}

const toggleTodoStatusAction = (ID: ID): IToggleTodoStatusAction => ({
  type: Actions.TOGGLE_TODO_STATUS,
  payload: ID,
});

export const toggleTodoStatus =
  (payload: IToggleTodoStatus) =>
  (dispatch: Dispatch<IToggleTodoStatusAction>) => {
    //step1:先将完成状态改变
    dispatch(toggleTodoStatusAction(payload.id));
    //step2:发起请求 改变后台数据
    toggleTodoStatusAPI(payload)
      .then(res => {
        console.log("res", res);
      })
      .catch(err => {
        console.log("err", err);
        //如果发生错误 改回来
        dispatch(toggleTodoStatusAction(payload.id));
      });
  };
